package cn.Controller;

import cn.CommonUtils.ApplicationConfigurationSingletonFactory;
import cn.CommonUtils.SignatureJwtUtils;
import cn.Dao.ApplicationConfigurationDao;
import cn.Dao.ConsumptionRecordDao;
import cn.Dao.EmployeeDao;
import cn.Dao.JobDao;
import cn.DynamicDataSource.DataSourceName;
import cn.Entity.Employee;
import cn.Entity.MaScanPoint;
import cn.MetaData.Annotation.ChooseDataSource;
import cn.MetaData.Annotation.SignatureJwt;
import cn.Service.GenerateReportToExcel;
import cn.Service.Impl.QueryDataByMutilDataSourceImpl;
import cn.Service.QueryDataByMutilDataSource;
import com.alibaba.fastjson.JSONObject;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Slf4j
@Controller
public class FourthController {

    @RequestMapping("/fourth/test1")
    @ResponseBody
    @SignatureJwt
    public JSONObject test1Proc(String id, String name , HttpServletRequest request , HttpServletResponse response , String jwt) {

        JSONObject result = new JSONObject();
        result.put("status", "success");

        log.info("############ this is fourth test procduce ... ");

        return result;
    }

    @RequestMapping("/fourth/login")
    @ResponseBody
    public JSONObject test1Proc( String name , String pwd , HttpServletRequest request , HttpServletResponse response ) {

        JSONObject result = new JSONObject();

        if ("tom".equals(name) && "123".equals(pwd)) {
            String jwt = SignatureJwtUtils.generateJWT("secret", SignatureAlgorithm.HS384, 30 * 60 * 1000L, null, null);
            result.put("status", "success");
            result.put("jwt", jwt);
            return result;
        }

        result.put("status", "fail");

        log.info("############ this is fourth test procduce ... ");

        return result;
    }


    /**
     * 在使用jwt时，用@PathVariable风格接收参数要注意 jwt token 会以 . 被分为三段
     * @param id
     * @param name
     * @param request
     * @param response
     * @param jwt
     * @return
     */
    @RequestMapping("/fourth2/{jwt}")
    @ResponseBody
    @SignatureJwt
    public JSONObject test1Proc2(String id, String name , HttpServletRequest request , HttpServletResponse response , @PathVariable(name = "jwt") String jwt) {

        JSONObject result = new JSONObject();
        result.put("status", "success");

        log.info("############ this is fourth test procduce . 2 .. ");

        return result;
    }

    @Autowired
    private EmployeeDao employeeDao;

    @Autowired
    private ApplicationConfigurationDao applicationConfigurationDao;

    @Autowired
    private JobDao jobDao;

    /**
     * 默认数据源
     * @return
     */
    @RequestMapping("/fourth/get1")
    @ResponseBody
    public JSONObject testProc3(){
        JSONObject result = new JSONObject();
        result.put("name", "TOM");

        List<Employee> employeeList = employeeDao.findAll();

        employeeList.forEach(i->{
            log.info(i.toString());
        });

        result.put("employee", employeeList);
        return result;
    }

    /**
     * 次数据源
     * @return
     */
    @RequestMapping("/fourth/get2")
    @ResponseBody
    @ChooseDataSource(dataSourceName = "MinorDatasource")
    public JSONObject testProc4(){
        JSONObject result = new JSONObject();
        result.put("name", "Jay");
        applicationConfigurationDao.findAll().forEach(i->{
            log.info(i.toString());
        });
        result.put("application", applicationConfigurationDao.findAll());
        return result;
    }

    /**
     * 主数据源
     * @return
     */
    @RequestMapping("/fourth/get3")
    @ResponseBody
    @ChooseDataSource()
    public JSONObject testProc5(){
        JSONObject result = new JSONObject();
        result.put("name", "Jay");
        applicationConfigurationDao.findAll().forEach(i->{
            log.info(i.toString());
        });
        return result;
    }

    /**
     * 第三数据源
     */

    @RequestMapping("/fourth/get4")
    @ResponseBody
    @ChooseDataSource(dataSourceName = "ThirdDatasource")
    public JSONObject testProc6(){
        JSONObject result = new JSONObject();
        result.put("name", "Jay");
        jobDao.findAll().forEach(i->{
            log.info(i.toString());
        });
        return result;
    }


    @Autowired
    private ConsumptionRecordDao consumptionRecordDao;

    @RequestMapping("/fifth/get1")
    @ResponseBody
//    @ChooseDataSource()
    public JSONObject testProc7(){
        JSONObject result = new JSONObject();

        result.put("data", queryDataByMutilDataSource.listAllConsumptionRecord());

       /* consumptionRecordDao.selectList(null).forEach(i -> {

        });*/

        return result;
    }

    @Autowired
    private QueryDataByMutilDataSourceImpl queryDataByMutilDataSource;

    @RequestMapping("/fifth/get2")
    @ResponseBody
//    @ChooseDataSource(dataSourceName = "MinorDatasource")
    public JSONObject testProc8(){
        JSONObject result = new JSONObject();

//        result.put("data",consumptionRecordDao.selectOne(null));

        result.put("data", queryDataByMutilDataSource.listAllConsumerBasicInfo());

       /* consumptionRecordDao.selectList(null).forEach(i -> {

        });*/

        return result;
    }

    @RequestMapping("/fifth/get3")
    @ResponseBody
//    @ChooseDataSource(dataSourceName = "ThirdDatasource")
    public JSONObject testProc9(){
        JSONObject result = new JSONObject();

        result.put("data",queryDataByMutilDataSource.listAllMaScanPoint());
       /* consumptionRecordDao.selectList(null).forEach(i -> {

        });*/

        return result;
    }

    @Autowired
    private GenerateReportToExcel generateReportToExcel;
    @RequestMapping("/fifth/get4")
    @ResponseBody
//    @ChooseDataSource(dataSourceName = "ThirdDatasource")
    public JSONObject testProc10(){
        JSONObject result = new JSONObject();

        log.warn("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ start"+new Date().toLocaleString()+"  ,  "+System.currentTimeMillis());
        generateReportToExcel.generatePlatinumBagConsumeScanCodeRecord();
        log.warn("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ end"+new Date().toLocaleString()+"      ,     "+System.currentTimeMillis());

        result.put("status", "success");
        return result;
    }

    @RequestMapping("/fifth/get5")
    @ResponseBody
//    @ChooseDataSource(dataSourceName = "ThirdDatasource")
    public JSONObject testProc11(){
        JSONObject result = new JSONObject();

        log.warn("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ start"+new Date().toLocaleString()+"  ,  "+System.currentTimeMillis());
        generateReportToExcel.generatePlatinumBagConsumeScanCodeRecord2();
        log.warn("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ end"+new Date().toLocaleString()+"      ,     "+System.currentTimeMillis());

        result.put("status", "success");
        return result;
    }


    @RequestMapping("/fifth/get6")
    @ResponseBody
//    @ChooseDataSource(dataSourceName = "ThirdDatasource")
    public JSONObject testProc12(){
        JSONObject result = new JSONObject();

        log.warn("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ start"+new Date().toLocaleString()+"  ,  "+System.currentTimeMillis());

        String innerCodeStr = "02238816644002293166," +
                "06710725609531127854," +
                "00631198411087130659";
        List<MaScanPoint> maScanPointList = queryDataByMutilDataSource.listAllMaScanPointInInnerCodes(innerCodeStr);


        log.warn("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ end"+new Date().toLocaleString()+"      ,     "+System.currentTimeMillis());

        result.put("status", "success");
        result.put("data", maScanPointList);
        return result;
    }

    @RequestMapping("/fifth/get7")
    @ResponseBody
//    @ChooseDataSource(dataSourceName = "ThirdDatasource")
    public JSONObject testProc113(@RequestParam(required = true )String param01){
        JSONObject result = new JSONObject();

        if (! "R".equals(param01)) {
            result.put("status", "fail");
            result.put("message", "未传入正确指令，故程序不运行。");
            return result;
        }


        log.warn("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ start"+new Date().toLocaleString()+"  ,  "+System.currentTimeMillis());
        generateReportToExcel.generatePlatinumBagConsumeScanCodeRecord3();
        log.warn("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ end"+new Date().toLocaleString()+"      ,     "+System.currentTimeMillis());

        result.put("status", "success");
        return result;
    }

    @RequestMapping("/fifth/get8")
    @ResponseBody
//    @ChooseDataSource(dataSourceName = "ThirdDatasource")
    public JSONObject testProc114(@RequestParam(required = true )String param01){
        JSONObject result = new JSONObject();

        if (! "R".equals(param01)) {
            result.put("status", "fail");
            result.put("message", "未传入正确指令，故程序不运行。");
            return result;
        }

        log.warn("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ start"+new Date().toLocaleString()+"  ,  "+System.currentTimeMillis());
        generateReportToExcel.generatePlatinumBagRedEnvelopeRecord();
        log.warn("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ end"+new Date().toLocaleString()+"      ,     "+System.currentTimeMillis());

        result.put("status", "success");
        return result;
    }


    /**
     * 下载Excel
     * @param request
     * @param response
     * @throws IOException
     */
    @GetMapping("/download/platinumbagredenvelope")
    public void listAllEmployeeOfExcel(HttpServletRequest request , HttpServletResponse response) throws IOException {

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String reportDate = simpleDateFormat.format(new Date());

        String reportLocalPath = ApplicationConfigurationSingletonFactory.getValueOfConfiguration("ReportLocalPath");

        log.info("报表存放路径："+ reportLocalPath);
        FileInputStream fileInputStream = new FileInputStream(reportLocalPath + "PlatinumBagRedEnvelopeRecord" + reportDate + ".xlsx");
        File file = new File(reportLocalPath + "PlatinumBagRedEnvelopeRecord" + reportDate + ".xlsx");


//      response输出流设置
        response.reset();
        response.setHeader("Content-disposition","attachment; filename="+"PlatinumBagRedEnvelopeRecord" + reportDate + ".xlsx");
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");



        byte fileBytes[] = new byte[(int) file.length()];
        fileInputStream.read(fileBytes, 0, (int) file.length());

        response.getOutputStream().write(fileBytes);

        response.getOutputStream().flush();
        response.getOutputStream().close();

    }

    /**
     * 下载Excel
     * @param request
     * @param response
     * @throws IOException
     */
    @GetMapping("/download/platinumbagconsumerecord")
    public void listAllEmployeeOfExcel2(HttpServletRequest request , HttpServletResponse response) throws IOException {

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String reportDate = simpleDateFormat.format(new Date());

        String reportLocalPath = ApplicationConfigurationSingletonFactory.getValueOfConfiguration("ReportLocalPath");

        log.info("报表存放路径："+ reportLocalPath);
        FileInputStream fileInputStream = new FileInputStream(reportLocalPath + "PlatinumBagVerifyConsumeRecord" + reportDate + ".xlsx");
        File file = new File(reportLocalPath + "PlatinumBagVerifyConsumeRecord" + reportDate + ".xlsx");


//      response输出流设置
        response.reset();
        response.setHeader("Content-disposition","attachment; filename="+"PlatinumBagVerifyConsumeRecord" + reportDate + ".xlsx");
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");



        byte fileBytes[] = new byte[(int) file.length()];
        fileInputStream.read(fileBytes, 0, (int) file.length());

        response.getOutputStream().write(fileBytes);

        response.getOutputStream().flush();
        response.getOutputStream().close();

    }

}
